<template>
    <div>
        <el-upload ref="uploadRef" :accept="accept" v-model:file-list="fileList" class="w-full" :auto-upload="false"
            :limit="limit" :multiple="multiple" :on-change="handleChange" :list-type="listType" :on-remove="handleRemove"
            :on-exceed="handleExceed">
            <el-button class="w-full">
                <el-icon>
                    <Plus class="fs-14" />
                </el-icon>
                添加附件
            </el-button>

            <template #file="{ file }">
                <div>
                    <img class="el-upload-list__item-thumbnail" crossorigin="anonymous" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </span>
                    </span>
                </div>
            </template>

        </el-upload>
    </div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, genFileId } from 'element-plus'

import blacklist from '../dialog/blacklist.vue'

const fileList = ref([])

const uploadRef = ref(null)


const props = defineProps({
    accept: {
        type: String,
        default: '.jpg,.jpeg,.png,.gif,.JPG,.JPEG,.PNG,.GIF'
    },
    base64File: {
        type: String
    },
    fileUrl: {
        type: String
    },
    limit: {
        type: [Number, String],
        default: 1
    },
    multiple: {
        type: Boolean,
        default: false
    },
    listType: {
        type: String,
        default: 'picture-card'
    }
})

const emits = defineEmits(['update:base64File'])

const handleChange = (file) => {
    console.log(2121, file)
    const rawFile = file.raw
    if (!rawFile) return
    const typeList = props.accept.split(',')
    const fileType = rawFile.name.substring(rawFile.name.indexOf('.'))

    if (typeList.every(i => i !== fileType)) {
        ElMessage.error('只能上传格式为图片的文件')
        fileList.value = []
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('只能上传大小为5M以内的图片')
        fileList.value = []
        return false
    }
    const imgFile = new FileReader()
    imgFile.readAsDataURL(rawFile)
    imgFile.onload = res => {
        const base64 = res.target.result.split('base64,')[1]
        emits('update:base64File', base64)
    }
    return true
}

const handleRemove = (file) => {
    const index = fileList.value.find(i => i.uid === file.uid)
    if (index!==-1) {
        fileList.value.splice(index, 1)
    }
    emits('update:base64File', '')
}

const handleExceed = (files) => {
    uploadRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value.handleStart(file)
}

function getBase64Image(img) {
    const canvas = document.createElement('canvas')
    canvas.width = img.width
    canvas.height = img.height
    const ctx = canvas.getContext('2d')
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
    const dataURL = canvas.toDataURL()
    return dataURL
}
// 将后端传过来的图片url转成base64
watch(() => props.fileUrl, (newval) => {
    if (newval) {
        const image = new Image()
        image.src = newval + '?v=' + Math.random()
        image.crossOrigin = 'anonymous'
        image.onload = function () {
            const fullbase64 = getBase64Image(image)
            const base64 = fullbase64.split('base64,')[1]
            emits('update:base64File', base64)
        }
        fileList.value.push({
            url: newval,
            uid: genFileId()
        })
    }
}, {
    immediate: true
})

</script>
<style lang="scss" scoped>
:deep(.el-upload) {
    width: 100%;
}

:deep(.el-button) {
    border-style: dashed;
}

:deep(.el-upload--picture-card) {
    height: 32px !important;
    width: 360px !important;
    border: none;
}
</style>